<?php

namespace adminApi\modules\product\controllers;

use adminApi\modules\product\models\Suppliers;
use common\components\fast_api\Controller;
use common\components\wtools\tools\ArrayHelper;
use common\components\wtools\tools\Model;
use common\components\wtools\validators\Mobile;
use common\components\wtools\validators\Password;
use common\components\wtools\validators\Username;
use common\datas\Enums;
use common\Tools;
use yii\base\DynamicModel;
use yii\data\ActiveDataProvider;

class SupplierController extends Controller
{
    /**
     * 列表
     * @desc 供应商列表
     * @param int $page 页码
     * @param int $pageSize 每页条数
     * @param string|null $name 供应商名
     * @param string|null $mobile 手机号
     * @param int|null $status 状态
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     */
    public function actionList($page = 1, $pageSize = 10, $name = null, $mobile = null, $status = null)
    {
        $query = Suppliers::find();
        if ($name) {
            $query->andFilterWhere(['like', 'name', $name]);
        }
        if ($mobile) {
            $query->andFilterWhere(['like', 'mobile', $mobile]);
        }
        if ($status) {
            $query->andFilterWhere(['status' => $status]);
        }
        $apiPageData = $this->apiPageData($query, $page, $pageSize);
        $items = [];
        foreach ($apiPageData->dataProvider->models as $k => $v) {
            /** @var Suppliers $v */
            $m = [];
            $m['id'] = $v->id;
            $m['name'] = $v->name;
            $m['mobile'] = $v->mobile;
            $m['created_at'] = $v->created_at;
            $m['_created_at'] = date("Y-m-d H:i", $v->created_at);
            $m['status'] = $v->status;
            $m['_status'] = Enums::getStatusDesc()[$v->status];
            $items[] = $m;
        }
        $data = [
            'items' => $items,
            '_meta' => $apiPageData->meta,
        ];
        return $this->apiSuccess($data, '获取列表成功');
    }

    /**
     * 添加or修改供应商
     * @desc post
     * @param string $mobile
     * @param string $name
     * @param int $status
     * @param string $password
     * @param int $id
     * @return array
     */
    public function actionAddOrEdit($mobile, $name, $status, $password = '', $id = 0)
    {
        $rules = [
            [['mobile', 'name', 'status'], 'required'],
            [['mobile', 'name', 'status', 'password'], 'trim'],
            ['status', 'in', 'range' => array_keys(Enums::getStatusDatas())],
            ['mobile', Mobile::class],
            ['name', Username::class],
            ['password', Password::class],
        ];
        if ($id > 0) {
            $supplier = Suppliers::findOne($id);
            $rules = ArrayHelper::merge($rules, [
                ['mobile', 'unique', 'targetClass' => Suppliers::class, 'targetAttribute' => 'mobile', 'message' => '该手机号已存在', 'filter' => ['<>', 'id', $id]],
                ['name', 'unique', 'targetClass' => Suppliers::class, 'targetAttribute' => 'name', 'message' => '该账号已存在', 'filter' => ['<>', 'id', $id]],
            ]);
        } else {
            $supplier = new Suppliers();
            $supplier->generateToken();
            $rules = ArrayHelper::merge($rules, [
                ['password', 'required'],
                ['mobile', 'unique', 'targetClass' => Suppliers::class, 'targetAttribute' => 'mobile', 'message' => '该手机号已存在。'],
                ['name', 'unique', 'targetClass' => Suppliers::class, 'targetAttribute' => 'name', 'message' => '该账号已存在。'],
            ]);
        }
        $model = DynamicModel::validateData(['mobile' => $mobile, 'name' => $name, 'status' => $status, 'password' => $password], $rules);
        if (!$model->validate()) {
            return $this->apiError(Model::getModelError($model));
        }
        $supplier->mobile = $model->mobile;
        $supplier->name = $model->name;
        $supplier->status = $model->status;
        if ($model->password) {
            $supplier->generatePassword($model->password);
        }
        if (!$supplier->save()) {
            return $this->apiError(Model::getModelError($supplier));
        }
        return $this->apiSuccess([
            'adminer' => $supplier,
        ], "保存成功");
    }

    /**
     * 查询供应商
     * @desc 后台搜索供应商
     * @param string $name
     * @param int $id
     * @return array
     * @return array list
     */
    public function actionSearch($name = '', $id = 0)
    {
        $query = Suppliers::find();
        $query->andFilterWhere(['status' => Enums::ACTIVE]);
        if ($name) {
            $query->andFilterWhere(['or', ['like', 'name', $name], ['like', 'mobile', $name]]);
        }
        if ($id > 0) {
            $query->andWhere(['id' => $id]);
        }
        $suppliers = $query->limit(10)->all();
        $list = [];
        foreach ($suppliers as $k => $v) {
            $item = [
                'value' => $v->id,
                'label' => "{$v->mobile} | ".$v->name,
            ];
            $list[] = $item;
        }
        return $this->apiSuccess([
            'list' => $list
        ]);
    }
}
